/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmMain.java
 *
 * Created on 27/04/2011, 12:44:41 PM
 */
package com.loli.hernandez.presentacion;

import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import com.loli.hernandez.modelo.DataManager;

import com.loli.hernandez.modelo.beans.Database;
import com.loli.hernandez.modelo.beans.DatabaseTable;
import com.loli.hernandez.modelo.StoredProcedureGenerator;
import com.loli.hernandez.modelo.TableColumnPeer;
import com.loli.hernandez.modelo.beans.TableColumn;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.net.URL;
import java.text.MessageFormat;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.pushingpixels.substance.api.skin.SubstanceOfficeBlue2007LookAndFeel;

/**
 *
 * @author Administrator
 */
public class frmMain1 extends javax.swing.JFrame {

    RSyntaxTextArea txtr = new RSyntaxTextArea(10, 5);
    private Database baseDatosSeleccionada = null;
    private DatabaseTable tablaSeleccionada = null;
    private ArrayList<TableColumn> columnasTabla = null;
//    new java.awt.event.ActionListener() {
//            public void actionPerformed(java.awt.event.ActionEvent evt) {
//                chkDeleteProcActionPerformed(evt);
//            }
//        }

    class EventoCheck implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() instanceof JCheckBox) {


                JCheckBox check = (JCheckBox) e.getSource();

                //Recupero la posición
                //  System.out.println(check.getName());
                int pos = Integer.parseInt(check.getName());

                if (check.isSelected()) {
                    TableColumn columna = columnasTabla.get(pos);
                    columna.setAllowedForCodeGeneration(true);
                    columnasTabla.set(pos, columna);
                } else {

                    TableColumn columna = columnasTabla.get(pos);
                    columna.setAllowedForCodeGeneration(false);
                    columnasTabla.set(pos, columna);
                }


            }
        }
    }

    class EventoCheckarTodos implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            boolean seleccionado = ((JCheckBox) e.getSource()).isSelected();
            for (Component c : panelColumnas.getComponents()) {

                if (c instanceof JCheckBox) {
                    JCheckBox check = (JCheckBox) c;
                    int pos = Integer.parseInt(check.getName());
                    //-1 es el check de selecccionar todos
                    if (pos != -1) {
                        if (seleccionado) {

                            TableColumn columna = columnasTabla.get(pos);
                            columna.setAllowedForCodeGeneration(true);
                            columnasTabla.set(pos, columna);
                            check.setSelected(true);

                        } else {
                            TableColumn columna = columnasTabla.get(pos);
                            columna.setAllowedForCodeGeneration(false);
                            columnasTabla.set(pos, columna);
                            check.setSelected(false);
                        }
                    }

                }
            }

            //  System.out.println("hola");
        }
    }

    /** Creates new form frmMain */
    public frmMain1() {
        initComponents();


        txtr.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_SQL);

        txtr.setColumns(20);
        txtr.setFont(new java.awt.Font("Courier New", 0, 13));
        txtr.setRows(5);
        jScrollPane1.setViewportView(txtr);

        //Configurar el formulario para maximizado en la ventana
         setExtendedState(JFrame.MAXIMIZED_BOTH);

        //Colocando un ícono para el formulario
        URL ruta = getClass().getResource("/com/loli/hernandez/presentacion/"
                + "48/mysql_admin.png");

        ImageIcon icono = new ImageIcon(ruta);
        this.setIconImage(icono.getImage());

        jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    }

    private void cargarDatosDelServidor(DataManager dataManager) throws SQLException {
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Bases de datos");
        for (Database bd : dataManager.showAllDatabases()) {
            DefaultMutableTreeNode nodoBDs = new DefaultMutableTreeNode(bd);
        
            dataManager.setDatabase(bd);
            for (DatabaseTable tabla : dataManager.getTablesFromDatabase()) {
                DefaultMutableTreeNode nodoTablas = new DefaultMutableTreeNode(tabla);
                nodoBDs.add(nodoTablas);
            }
            top.add(nodoBDs);
        }


        DefaultTreeModel modelo = new DefaultTreeModel(top);
    
        jTree1.setModel(modelo);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtServidor = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtPuerto = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtContrasena = new javax.swing.JPasswordField();
        btnConectar = new javax.swing.JButton();
        btnGenerar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        chkDeleteProc = new javax.swing.JCheckBox();
        chkUpdateProc = new javax.swing.JCheckBox();
        chkSelectProc = new javax.swing.JCheckBox();
        chkInsertProc = new javax.swing.JCheckBox();
        chkDetailsProc = new javax.swing.JCheckBox();
        jPanel3 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtNomProcUpdate = new javax.swing.JTextField();
        txtNomProcSelect = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtNomProcInsert = new javax.swing.JTextField();
        txtNomProcDelete = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        txtPrefijoProc = new javax.swing.JTextField();
        txtNomProcDetalles = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        panelColumnas = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Generador de procedimientos almacenados MySQL : Néstor Hernández Loli");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("¡Empiece aquí! Llene los datos de su conexión"));

        txtServidor.setText("localhost");

        jLabel1.setText("Servidor:");

        jLabel2.setText("Puerto:");

        txtPuerto.setText("3306");

        jLabel3.setText("Usuario:");

        txtUsuario.setText("root");

        jLabel4.setText("Contraseña:");

        btnConectar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/loli/hernandez/presentacion/24x24/categories/applications-internet.png"))); // NOI18N
        btnConectar.setText("Conectar");
        btnConectar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnConectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConectarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                            .addComponent(txtPuerto, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                            .addComponent(txtServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(txtContrasena, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(btnConectar, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(txtServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(txtContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnConectar)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        btnGenerar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/loli/hernandez/presentacion/24x24/categories/package_development.png"))); // NOI18N
        btnGenerar.setText("Generar");
        btnGenerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("¿Qué tipo de procs. desea generar?"));

        chkDeleteProc.setSelected(true);
        chkDeleteProc.setText("Procedimiento DELETE");
        chkDeleteProc.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        chkDeleteProc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkDeleteProcActionPerformed(evt);
            }
        });

        chkUpdateProc.setSelected(true);
        chkUpdateProc.setText("Procedimiento UPDATE");
        chkUpdateProc.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        chkUpdateProc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkUpdateProcActionPerformed(evt);
            }
        });

        chkSelectProc.setSelected(true);
        chkSelectProc.setText("Procedimiento SELECT");
        chkSelectProc.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        chkSelectProc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkSelectProcActionPerformed(evt);
            }
        });

        chkInsertProc.setSelected(true);
        chkInsertProc.setText("Procedimiento INSERT");
        chkInsertProc.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        chkInsertProc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkInsertProcActionPerformed(evt);
            }
        });

        chkDetailsProc.setSelected(true);
        chkDetailsProc.setText("Procedimiento Detalles por código");
        chkDetailsProc.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        chkDetailsProc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkDetailsProcActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chkInsertProc)
                    .addComponent(chkSelectProc)
                    .addComponent(chkUpdateProc)
                    .addComponent(chkDeleteProc)
                    .addComponent(chkDetailsProc))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chkInsertProc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkSelectProc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkUpdateProc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkDeleteProc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkDetailsProc)
                .addContainerGap(48, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Puede escoger los nombres para los procs. alm"));

        jLabel9.setText("Nombre para el proc. SELECT");

        jLabel8.setText("Nombre para el proc. INSERT");

        jLabel11.setText("Nombre para el proc. DELETE");

        txtNomProcUpdate.setText("_Actualizar_");

        txtNomProcSelect.setText("_Listar_");

        jLabel10.setText("Nombre para el proc. UPDATE");

        txtNomProcInsert.setText("_Registrar_");

        txtNomProcDelete.setText("_Borrar_");

        jLabel12.setText("Puede elegir un prefijo (Ejm. USP):");

        txtPrefijoProc.setText("USP");

        txtNomProcDetalles.setText("_Por_Codigo");

        jLabel13.setText("Nombre para el proc. Detalles");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtNomProcDelete, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(txtNomProcUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(txtNomProcSelect, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(txtNomProcInsert, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(txtPrefijoProc, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addComponent(txtNomProcDetalles, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNomProcInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNomProcSelect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNomProcUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNomProcDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNomProcDetalles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtPrefijoProc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jXLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/loli/hernandez/presentacion/48/mysql_admin.png"))); // NOI18N
        jXLabel1.setLineWrap(true);
        jXLabel1.setText("MySQLProcAlmGenerator es un proyecto de código libre: Ayuda a generar procedimientos almacenados estándares en tablas de una BD MySQL. El tiempo ahorrado puede emplearlo para su disfrute o para darle apoyo a este proyecto. Un email, una sonrisa serán bien recibidas como también un par de euros :)  Importante: Recomiendo para la ejecución CORRECTA de este código usar MySQL Query Browser o MySQL Workbench NO MySQL Front por favor");
        jXLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jXLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Bases de datos");
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree1.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() {
            public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) {
                jTree1TreeCollapsed(evt);
            }
            public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {
                jTree1TreeExpanded(evt);
            }
        });
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane4.setViewportView(jTree1);

        panelColumnas.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccionar las columnas"));
        panelColumnas.setLayout(new java.awt.GridLayout(12, 2, 6, 2));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jXLabel1, 0, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(34, 34, 34)
                                .addComponent(btnGenerar))
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(panelColumnas, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(panelColumnas, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnGenerar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private DataManager getDataManager() {
        String server, user, password, port;
        server = txtServidor.getText();
        user = txtUsuario.getText();
        password = new String(txtContrasena.getPassword());
        port = txtPuerto.getText();

        DataManager dataManager = new DataManager(server, port, user, password);
        return dataManager;
    }
    private void btnConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConectarActionPerformed

        if (panelConexionValido()) {
            DataManager dataManager = getDataManager();
            try {
                if(dataManager==null) {
                    JOptionPane.showMessageDialog(null, "");
                }
                cargarDatosDelServidor(dataManager);

            } catch (SQLException e) {
                if (e.getErrorCode() == 1045) {
                    JOptionPane.showMessageDialog(this, "Usuario o contraseña incorrectos."
                            + "\nVerifique que los datos sean correctos", "Error de conexión", JOptionPane.ERROR_MESSAGE);

                }
                if (e.getErrorCode() == 0) {
                    JOptionPane.showMessageDialog(this, "No se pudo encontrar el servicio de MySQL.\n"
                            + "Verifique que el servicio MySQL este activo en el sistema", "Error de conexíón",
                            JOptionPane.ERROR_MESSAGE);
                }

            }
        }
    }//GEN-LAST:event_btnConectarActionPerformed

    private boolean panelConexionValido() {
        boolean valido = true;

        String msg = "";
        String necesario = "* El campo {0} es necesario";
        if (txtServidor.getText().trim().isEmpty()) {
            msg += MessageFormat.format(necesario, "Servidor") + "\n";
        }

        if (txtUsuario.getText().trim().isEmpty()) {
            msg += MessageFormat.format(necesario, "Usuario") + "\n";
        }
        if (txtPuerto.getText().trim().isEmpty()) {
            msg += MessageFormat.format(necesario, "Puerto") + "\n";
        }

        if (!msg.trim().isEmpty()) {
            valido = false;
            JOptionPane.showMessageDialog(this, msg, "Errores", JOptionPane.WARNING_MESSAGE);
        }
        return valido;
    }

    private boolean panelesOpcionesValido() {
        boolean valido = true;

        String msg = "";

        String necesario = "* El campo {0} es necesario";
        if (txtNomProcDelete.getText().trim().isEmpty() && chkDeleteProc.isSelected()) {
            msg += MessageFormat.format(necesario, "Nombre de proc. DELETE") + "\n";
        }

        if (txtNomProcDetalles.getText().trim().isEmpty() && chkDetailsProc.isSelected()) {
            msg += MessageFormat.format(necesario, "Nombre de proc. Detalles por código") + "\n";
        }
        if (txtNomProcInsert.getText().trim().isEmpty() && chkInsertProc.isSelected()) {
            msg += MessageFormat.format(necesario, "Nombre de proc. INSERT") + "\n";
        }

        if (txtNomProcSelect.getText().trim().isEmpty() && chkSelectProc.isSelected()) {
            msg += MessageFormat.format(necesario, "Nombre de proc. SELECT") + "\n";
        }
        if (txtNomProcUpdate.getText().trim().isEmpty() && chkUpdateProc.isSelected()) {
            msg += MessageFormat.format(necesario, "Nombre de proc. UPDATE") + "\n";
        }

        if (!msg.trim().isEmpty()) {
            valido = false;
            JOptionPane.showMessageDialog(this, msg, "Errores", JOptionPane.WARNING_MESSAGE);
        }
        return valido;
    }
    private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarActionPerformed
        if (baseDatosSeleccionada != null && tablaSeleccionada != null && columnasTabla != null) {
            int colsSelecc = 0;

            for (TableColumn col : columnasTabla) {
                if (col.isAllowedForCodeGeneration()) {

                    colsSelecc++;

                }
            }
            if (colsSelecc == 0) {
                JOptionPane.showMessageDialog(null, "Al menos una columna debe estar seleccionada", "Información",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            DataManager dataManager = getDataManager();
            dataManager.setDatabase(baseDatosSeleccionada);
            try {
                StoredProcedureGenerator procGen =
                        new StoredProcedureGenerator(dataManager);

                //Asignamos las columnas para generar código
                procGen.setTableColumnList(columnasTabla);
                procGen.setDeleteProcName(txtNomProcDelete.getText());
                procGen.setInsertProcName(txtNomProcInsert.getText());
                procGen.setSelectProcName(txtNomProcSelect.getText());
                procGen.setUpdateProcName(txtNomProcUpdate.getText());
                procGen.setDetailsProcName(txtNomProcDetalles.getText());
                procGen.setProcedurePrefix(txtPrefijoProc.getText());
                String proc = "";
                if (chkInsertProc.isSelected()) {
                    proc = procGen.getInsert_StoredProcedure(tablaSeleccionada) + "\n";
                }
                if (chkSelectProc.isSelected()) {
                    proc += procGen.getSelectAll_StoredProcedure(tablaSeleccionada) + "\n";
                }
                if (chkDetailsProc.isSelected()) {
                    proc += procGen.getGetDetailsById_StoredProcedure(tablaSeleccionada) + "\n";
                }
                if (chkUpdateProc.isSelected()) {
                    proc += procGen.getUpdate_StoredProcedure(tablaSeleccionada) + "\n";
                }
                if (chkDeleteProc.isSelected()) {
                    proc += procGen.getDelete_StoredProcedure(tablaSeleccionada) + "\n";
                }


                txtr.setText(proc);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
            }
        }

    }//GEN-LAST:event_btnGenerarActionPerformed

    private void chkInsertProcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkInsertProcActionPerformed
        if (chkInsertProc.isSelected()) {
            txtNomProcInsert.setEnabled(true);
        } else {
            txtNomProcInsert.setEnabled(false);
        }
    }//GEN-LAST:event_chkInsertProcActionPerformed

    private void chkSelectProcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkSelectProcActionPerformed
        if (chkSelectProc.isSelected()) {
            txtNomProcSelect.setEnabled(true);
        } else {
            txtNomProcSelect.setEnabled(false);
        }
    }//GEN-LAST:event_chkSelectProcActionPerformed

    private void chkDetailsProcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkDetailsProcActionPerformed
        if (chkDetailsProc.isSelected()) {
            txtNomProcDetalles.setEnabled(true);
        } else {
            txtNomProcDetalles.setEnabled(false);
        }
    }//GEN-LAST:event_chkDetailsProcActionPerformed

    private void chkUpdateProcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUpdateProcActionPerformed
        if (chkUpdateProc.isSelected()) {
            txtNomProcUpdate.setEnabled(true);
        } else {
            txtNomProcUpdate.setEnabled(false);
        }
    }//GEN-LAST:event_chkUpdateProcActionPerformed

    private void chkDeleteProcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkDeleteProcActionPerformed
        if (chkDeleteProc.isSelected()) {
            txtNomProcDelete.setEnabled(true);
        } else {
            txtNomProcDelete.setEnabled(false);
        }
    }//GEN-LAST:event_chkDeleteProcActionPerformed

private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
    //Limpiamos
//    baseDatosSeleccionada = null;
//    tablaSeleccionada = null;
//    columnasTabla = new ArrayList<TableColumn>();
    DefaultMutableTreeNode nodoTabla = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

    if (nodoTabla == null) {
        return;
    }

    try {
        if (nodoTabla.isLeaf()) { //Si se seleccionó un nodo interno y el nodo no tiene noditos
            tablaSeleccionada = (DatabaseTable) nodoTabla.getUserObject();
            DefaultMutableTreeNode nodoBaseDatos = (DefaultMutableTreeNode) nodoTabla.getParent();
            baseDatosSeleccionada = (Database) nodoBaseDatos.getUserObject();

            DataManager dataManager = getDataManager();
            dataManager.setDatabase(baseDatosSeleccionada);
            //Llenar el panel con las columnas de la tabla
            columnasTabla = TableColumnPeer.getColumnsFromTable(dataManager, tablaSeleccionada);

            //Quito todos los checks del panel
            panelColumnas.removeAll();
            JCheckBox checkTodos = new JCheckBox("Seleccionar todo");
            checkTodos.addActionListener(new EventoCheckarTodos());
            checkTodos.setName("-1");
            panelColumnas.add(checkTodos);

            int posicion = 0; //i va a ser un identificador único nos va a ayudar a el proceso de agregar 

            for (TableColumn col : columnasTabla) {
                JCheckBox check = new JCheckBox(col.getField());
                if (col.isPrimaryKey()) {
                    check.setText(col.getField() + "(ID)");
                } else if (col.isNullAllowed() == false) {
                    check.setText(col.getField() + "(Not null)");
                }
                check.setName(posicion + "");

                check.addActionListener(new EventoCheck());
                panelColumnas.add(check);
                posicion++;
            }

            //Actualizo la interfaz
            panelColumnas.updateUI();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }


}//GEN-LAST:event_jTree1ValueChanged

private void jTree1TreeExpanded(javax.swing.event.TreeExpansionEvent evt) {//GEN-FIRST:event_jTree1TreeExpanded
}//GEN-LAST:event_jTree1TreeExpanded

private void jTree1TreeCollapsed(javax.swing.event.TreeExpansionEvent evt) {//GEN-FIRST:event_jTree1TreeCollapsed
// TODO add your handling code here:
}//GEN-LAST:event_jTree1TreeCollapsed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        frmMain1.setDefaultLookAndFeelDecorated(true);

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                //   UIManager.setLookAndFeel(new SubstanceMarinerLookAndFeel());
                UIManager.setLookAndFeel(new SubstanceOfficeBlue2007LookAndFeel());
//                    UIManager.setLookAndFeel(new SubstanceDustLookAndFeel());
                } catch (Exception e) {
                }
                new frmMain1().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConectar;
    private javax.swing.JButton btnGenerar;
    private javax.swing.JCheckBox chkDeleteProc;
    private javax.swing.JCheckBox chkDetailsProc;
    private javax.swing.JCheckBox chkInsertProc;
    private javax.swing.JCheckBox chkSelectProc;
    private javax.swing.JCheckBox chkUpdateProc;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTree jTree1;
    private org.jdesktop.swingx.JXLabel jXLabel1;
    private javax.swing.JPanel panelColumnas;
    private javax.swing.JPasswordField txtContrasena;
    private javax.swing.JTextField txtNomProcDelete;
    private javax.swing.JTextField txtNomProcDetalles;
    private javax.swing.JTextField txtNomProcInsert;
    private javax.swing.JTextField txtNomProcSelect;
    private javax.swing.JTextField txtNomProcUpdate;
    private javax.swing.JTextField txtPrefijoProc;
    private javax.swing.JTextField txtPuerto;
    private javax.swing.JTextField txtServidor;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
